<template>
  <div>
    <div class="container" style="border-top: 1px solid #E6E6E6;width: 1500px;">
      <div class="user-index">
        <div class="user-index-header">
          <div class="user-index-header-title">
          </div>
        </div>
        <div class="user-index-body">
          <div class="user-index-body-form">
            <el-form ref="ruleFormRef" style="max-width: 100%; display: flex; flex-wrap: wrap; gap: 20px;"
              :model="ruleForm" label-width="auto" class="demo-ruleForm" status-icon>

              <el-form-item label="客户：">
                <el-select clearable style="width: 310px; margin-left: 10px;" placeholder="请选择客户">
                  <el-option v-for="customer in customers" :key="customer.id" :label="customer.supName"
                    :value="customer.supName" />
                </el-select>


              </el-form-item>

              <el-form-item label="单据日期" prop="date" style="margin-right: 60px;">
                <el-date-picker type="datetime" placeholder="选择日期与时间" clearable class="input" v-model="ruleForm.date"
                  style="width: 200px;" />
              </el-form-item>


              <el-form-item label="单据编号" prop="number" style="margin-right: 60px;">
                <el-input v-model="ruleForm.number" placeholder="自动生成单据编号" style="width: 200px;" readonly></el-input>
              </el-form-item>

              <el-form-item label="销售人员" prop="location">
                <el-select v-model="ruleForm.persons" placeholder="选择销售人员" style="width: 200px;">
                  <el-option label="小李" value="shanghai" v-for="person in persons" :lable="person.perName"
                    :value="person.perName" :key="person.id" />

                </el-select>
              </el-form-item>

              <div class="user-index-body-form-btn">
                <div class="user-index-body-form-btn-item">
                  <div class="ant-row-flex" style="display: flex; align-items: center;">
                    <div class="ant-col" style="margin-right: 10px;">
                      <el-button type="primary" class="ant-btn ant-btn-primary">
                        <el-icon class="el-icon-left">
                          <Plus />
                        </el-icon>
                        <span>插入行</span>
                      </el-button>
                    </div>
                    <div class="ant-col" style="margin-right: 10px;">
                      <el-button plain>扫码录入</el-button>
                    </div>
                    <div class="ant-col" style="margin-right: 10px;">
                      <el-button plain v-perm:sale:sale_order:insert:documents="insert">
                        <el-icon style="margin-right: 5px;">
                          <Clock />
                        </el-icon>
                        历史单据
                      </el-button>
                    </div>
                    <div class="ant-col">
                      <el-button plain>
                        <el-icon style="margin-right: 5px;">
                          <Grid />
                        </el-icon>
                        导入明细
                      </el-button>
                    </div>

                  </div>

                  <el-table border style="margin-top: 20px;width: 1500px;" :data="tableData">
                    <el-table-column type="selection" width="55" />

                    <el-table-column prop="barcode" label="条码">
                      <template #default="{ row }">
                        <el-input v-model="row.barcode" placeholder="请输入条码" class="center-textare"></el-input>
                        <el-button type="primary" class="ant-btn ant-btn-primary" style="margin-right: 10px;" plain
                          v-perm:salesale_order:insert:Saleinorder="Saleinorder">
                          <el-icon class="el-icon-left">
                            <Plus />
                          </el-icon>

                        </el-button>
                      </template>
                    </el-table-column>

                    <el-table-column prop="name" label="名称">
                      <template #default="{ row }">
                        <el-input v-model="row.name" placeholder="请输入名称" class="center-textare"></el-input>
                      </template>
                    </el-table-column>

                    <el-table-column prop="specification" label="规格">
                      <template #default="{ row }">
                        <el-input v-model="row.specification" placeholder="请输入规格" class="center-textare"></el-input>
                      </template>
                    </el-table-column>

                    <el-table-column prop="stock" label="库存">
                      <template #default="{ row }">
                        <el-input v-model="row.stock" type="number" placeholder="请输入库存"
                          class="center-textare"></el-input>
                      </template>
                    </el-table-column>

                    <el-table-column prop="unit" label="单位">
                      <template #default="{ row }">
                        <el-input v-model="row.unit" placeholder="请输入单位" class="center-textare"></el-input>
                      </template>
                    </el-table-column>

                    <el-table-column prop="quantity" label="数量">
                      <template #default="{ row }">
                        <el-input v-model="row.quantity" type="number" placeholder="请输入数量"
                          class="center-textare"></el-input>
                      </template>
                    </el-table-column>

                    <el-table-column prop="price" label="单价">
                      <template #default="{ row }">
                        <el-input v-model="row.price" type="number" placeholder="请输入单价"
                          class="center-textare"></el-input>
                      </template>
                    </el-table-column>

                    <el-table-column prop="amount" label="金额">
                      <template #default="{ row }">
                        <el-input v-model="row.amount" type="number" placeholder="请输入金额"
                          class="center-textare"></el-input>
                      </template>
                    </el-table-column>

                    <el-table-column prop="taxRate" label="税率">
                      <template #default="{ row }">
                        <el-input v-model="row.taxRate" placeholder="请输入税率" class="center-textare"></el-input>
                      </template>
                    </el-table-column>

                    <el-table-column prop="tax" label="税额">
                      <template #default="{ row }">
                        <el-input v-model="row.tax" type="number" placeholder="请输入税额" class="center-textare"></el-input>
                      </template>
                    </el-table-column>

                    <el-table-column prop="total" label="价税合计">
                      <template #default="{ row }">
                        <el-input v-model="row.total" type="number" placeholder="请输入价税合计"
                          class="center-textare"></el-input>
                      </template>
                    </el-table-column>

                    <el-table-column prop="remark" label="备注">
                      <template #default="{ row }">
                        <el-input v-model="row.remark" placeholder="请输入备注" class="center-textare"></el-input>
                      </template>
                    </el-table-column>

                  </el-table>

                  <div class="input-group" style="margin-top: 10px; border: 1px solid #E6E6E6;">
                    <div class="body-group-text">
                      <el-input type="textarea" placeholder="请输入备注信息" class="center-textare" />
                    </div>
                  </div>

                </div>
              </div>

              <div class="index-body tb">
                <el-form-item label="优惠率：" style="margin-right: 120px;">
                  <el-input style="width: 185px">
                    <template #suffix>
                      <span>%</span>
                    </template>
                  </el-input>
                </el-form-item>
                <el-form-item label="收款优惠：" style="margin-right: 120px;">
                  <el-input style="width: 240px"></el-input>
                </el-form-item>
                <el-form-item label="优惠后金额：">
                  <el-input style="width: 240px"></el-input>
                </el-form-item>

              </div>

              <div class="index-body zb">
                <el-form-item label="结算账户：" style="margin-right: 120px;">
                  <el-select clearable style="width: 200px; " placeholder="请选择客户">
                    <el-option v-for="account in accounts" :key="account.id" :label="account.name"
                      :value="account.name" />
                  </el-select>
                </el-form-item>
                <el-form-item label="收取定金：" style="margin-right: 100px;">
                  <el-input style="width: 240px"></el-input>
                </el-form-item>
              </div>

              <div class="ant-coloery" style="margin-right: 10px;">
                <el-form-item label="附件：">
                  <el-button plain>
                    <el-icon style="margin-right: 10px;">
                      <MessageBox />
                    </el-icon>上传附件
                  </el-button>
                </el-form-item>
              </div>

              <div class="index-body wb" style="margin-top: 100px;margin-left: 1250px;">
                <div class="ant-coloery" style="margin-right: 10px;">
                  <el-button>取消</el-button>
                </div>
                <div class="ant-coloery" style="margin-right: 10px;">
                  <el-button>保存并审核</el-button>
                </div>
                <div class="ant-coloery" style="margin-right: 10px;">
                  <el-button type="primary" @click="submitForm">保存</el-button>
                </div>
              </div>

            </el-form>
          </div>

        </div>
      </div>
    </div>
  </div>
  
  <el-dialog :destroy-on-close="true" :title="title" v-model="visible" width="70%"
    style="margin-left: 350px;margin-top: 200px">
    <router-view @close="close" @saveSaleinorder="saveSaleinorder" :data="data"></router-view>
  </el-dialog>
</template>


<script lang="ts" setup>
import { reactive, ref, onMounted } from 'vue';
import type { FormInstance } from 'element-plus';
import router from '@/router';
import request from '@/api/request';

const visible = ref(false);
const title = ref("");
const data = ref({});
const saleinoerder = ref({})
// 定义表单数据结构
interface RuleForm {
  name: string;
  date: string;
  location: string;
  number: string;
}
const insert = (p) => {
  title.value = p.cname;
  visible.value = true;
  router.push(p.path);
};
// 表单引用
const ruleFormRef = ref<FormInstance>();
// 表单数据

const close = () => {
  visible.value = false;
};
// 页面加载时生成订单编号
onMounted(() => {
  // 从 localStorage 获取当前订单编号，如果不存在则设置为 1
  let currentOrderNumber = parseInt(localStorage.getItem('orderNumber') || '1', 10);
  ruleForm.number = String(currentOrderNumber).padStart(10, '0'); // 生成 10 位数的订单编号
  currentOrderNumber++; // 递增订单编号
  localStorage.setItem('orderNumber', currentOrderNumber.toString()); // 保存到 localStorage
});

const tableData = ref([
  { barcode: '', name: '', specification: '', stock: '', unit: '', quantity: '', price: '', amount: '', taxRate: '', tax: '', total: '', remark: '' }
  // 其他初始值
]);

const add = () => {
  tableData.value.push({

    barcode: '', name: '', specification: '', stock: '', unit: '', quantity: '', price: '', amount: '', taxRate: '', tax: '', total: '', remark: ''
  });
}

const Saleinorder = (p) => {
  title.value = p.cname;
  visible.value = true;
  router.push(p.path);
}



const ruleForm = reactive<RuleForm>({
  name: '',
  date: new Date().toISOString().slice(0, 19), // 设置为当前的日期和时间（精确到时分秒）
  number: '',
  location: ''
});

// 重置表单
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};
const customers = ref([]); // 存储客户数据
const loadCustomers = () => {
  request({
    url: '/basic/vendor/list',
    method: 'get'
  }).then(res => {

    customers.value = res.data; // 更新客户数据
  }).catch(err => {
    console.error(err);
  });
};
loadCustomers();
const accounts = ref([]); // 存储结算账户数据
const loadAccounts = () => {
  request({
    url: '/basic/account/list',
    method: 'get'
  }).then(res => {

    accounts.value = res.data; // 更新结算账户数据
  }).catch(err => {
    console.error(err);
  });
};
loadAccounts();
const submitForm = () => {
  const data = {
    erpDepotHead: {
      number: ruleForm.number, // 自动生成的编号
      date: ruleForm.date,
      location: ruleForm.location
    },
    erpDepotItem: {
      materialId: '588',

    }
  };

  request({
    url: '/sale/add',
    method: 'post',
    data: data,
    headers: {
      'Content-Type': 'application/json'
    }
  }).then(res => {
    console.log(res);

  }).catch(err => {
    console.error(err);
    alert('提交失败: ' + err.message);
  });
};

const persons = ref([]); // 存储销售人员数据
const loadPersons = () => {
  request({
    url: '/basic/person/list',
    method: 'get'
  }).then(res => {

    persons.value = res.data; // 更新销售人员数据
  }).catch(err => {
    console.error(err);
  });
};
loadPersons();
let saveSaleinorder = (item) => {
  console.log("欲保存的条目:", item); // 打印出选中的条目
  
  // 查找是否已经存在该条目
  const existingIndex = tableData.value.findIndex(row => row.barcode === item.barCode);
  
  console.log("查找到的索引:", existingIndex); // 打印出查找到的索引

  const newData = {
    barcode: item.barCode,
    name: item.materialName,
    specification: item.standard,
    stock: item.totalOperNumber,
    unit: item.commodityUnit,
  };

  if (existingIndex !== -1) {
    // 如果存在，更新现有行
    tableData.value[existingIndex] = { ...tableData.value[existingIndex], ...newData };
    console.log("更新现有行:", tableData.value[existingIndex]); // 打印更新后的行
  } else {
    // 这里不添加新行，您可以选择不做任何操作或者给出提示
    console.warn(`条码 ${item.barCode} 未找到，无法更新。`);
    ElMessage.warning(`条码 ${item.barCode} 未找到，无法更新。`);
  }
};










</script>
<style></style>
